<template>
	<div>
		<a-card :title="title">
			<template #extra>
				<a-button v-permission="permission.create" type="link" @click="addDictionary">
					<plus-outlined />新增
				</a-button>

				<template v-if="currentNode.id">
					<span v-permission="permission.update">
						<a-divider type="vertical" />
						<a-button type="link" @click="editDictionary(currentNode)">
							<edit-outlined />修改
						</a-button>
					</span>

					<span v-permission="permission.delete">
						<a-divider type="vertical" />

						<a-popconfirm title="确定要删除选中的记录吗？" ok-text="是" cancel-text="否" @confirm="deleteDictionary(currentNode.id)">
							<a-button danger type="link">
								<delete-outlined />删除
							</a-button>
						</a-popconfirm>
					</span>
				</template>
			</template>
			<a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="搜索" />
			<a-tree v-if="dictionaryTree.length" style="font-size: 16px;line-height: 20px;" :tree-data="dictionaryTree" :show-icon="true" :show-line="true" :block-node="true" :default-expand-all="defaultExpandAll" :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :check-strictly="true" @expand="onExpand" @select="selectTree">
				<template #title="{ name }">
					<span v-if="name.indexOf(searchValue) > -1">
						{{ name.substr(0, name.indexOf(searchValue)) }}
						<span style="color: #f50">{{ searchValue }}</span>
						{{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
					</span>
					<span v-else>{{ name }}</span>
				</template>
			</a-tree>
		</a-card>

		<a-modal v-model:visible="visible" :width="480" :title="`${formState.id ? '修改' : '添加'}分类`" @ok="saveDictionary">
			<a-form ref="formRef" layout="horizontal" :model="formState" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入'}">
					<a-input v-model:value="formState.name" />
				</a-form-item>
				<a-form-item label="上级分类">
					<a-tree-select v-model:value="formState.parent_id" show-search :dropdown-style="{}" tree-default-expand-all :tree-data="parentDictionaryTree" :field-names="{children: 'children',label: 'name',value: 'id'}" :expanded-keys="expandedKeys" tree-node-filter-prop="name"></a-tree-select>
				</a-form-item>
				<a-form-item label="计价方式" name="price_type">
					<a-radio-group v-model:value="formState.price_type">
						<a-radio :value="1">按月浮动</a-radio>
						<a-radio :value="2">按日浮动</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item label="备注" name="memo">
					<a-textarea v-model:value="formState.memo" />
				</a-form-item>

				<a-form-item label="上级分类" name="parent_id">
					<a-tree-select v-model:value="formState.parent_id" :show-search="true" :dropdown-style="{}" tree-default-expand-all :tree-data="parentTreeData" :field-names="{children: 'children',label: 'label',value: 'value'}" tree-node-filter-prop="label"></a-tree-select>
				</a-form-item>

				<a-form-item label="是否物料" name="is_leaf" :rules="{required:true, message:'请选择'}">
					<a-radio-group v-model:value="formState.is_leaf">
						<a-radio :value="1">是</a-radio>
						<a-radio :value="0">否</a-radio>
					</a-radio-group>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script setup>
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";

import { getCurrentInstance, onMounted, ref, computed, watch } from "vue";

const { proxy } = getCurrentInstance();

import { post, listToTree } from "../utils";

const props = defineProps({
	title: {
		type: String,
		required: true,
		default: ""
	},
	code: {
		type: String,
		required: true,
		default: ""
	},
	defaultExpandAll: {
		type: Boolean,
		required: true,
		default: true
	},
	permission: {
		type: Object,
		default() {
			return {};
		}
	}
});

const dictionaryRoot = ref({});

const dictionaryTree = ref([]);
const dictionaryList = ref([]);
const searchValue = ref('');

const getDictionaryTree = async () => {
	const { id: rootId } = dictionaryRoot.value;

	const data = await post("dictionary", { root_id: rootId });

	dictionaryList.value = data;
	const tree = listToTree(JSON.parse(JSON.stringify(data)), rootId);
	dictionaryTree.value = tree;
	filterTree(tree, searchValue.value);
};
const expandedKeys = ref([]);
const autoExpandParent = ref(false);
const onExpand = (keys) => {
	expandedKeys.value = keys;
	autoExpandParent.value = false;
};
watch(searchValue, value => {
	expandedKeys.value = [];
	const tree = listToTree(JSON.parse(JSON.stringify(dictionaryList.value)), dictionaryRoot.value.id);
	if (value) {
		filterTree(tree, value);
	}
	dictionaryTree.value = tree;
});
function filterTree(tree, searchValue) {
	return tree.filter(item => {
		if (item.children) {
			item.children = filterTree(item.children, searchValue);
		}
		if (!item.children || !item.children.length) {
			return item.name.toLowerCase().includes(searchValue.toLowerCase());
		} else {
			if (searchValue) {
				expandedKeys.value.push(item.id);
			}
			return true;
		}
	});
}

onMounted(async () => {
	const root = await post("dictionary/info", { code: props.code });
	dictionaryRoot.value = root;

	await getDictionaryTree();
});

const visible = ref(false);

const formState = ref({});

const currentNode = ref({});

const addDictionary = () => {
	const { is_leaf } = currentNode.value || {};
	if (is_leaf) {
		proxy.$message.error("此内容为物资，不允许创建下级物资分类");
		return false;
	}

	formState.value = {
		parent_id: currentNode.value?.id || dictionaryRoot.value.id,
		is_leaf: 0
	};

	visible.value = true;
};
const editDictionary = record => {
	formState.value = record;

	visible.value = true;
};

const deleteDictionary = id => {
	post("dictionary/delete", { id }).then(() => {
		proxy.$message.success("删除成功");

		getDictionaryTree();
	});
};

const formRef = ref();

const saveDictionary = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			params.code = props.code;

			post("dictionary/save", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					getDictionaryTree();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

const emit = defineEmits(["select"]);

const selectTree = key => {
	if (!key.length) return;

	const data = dictionaryList.value.find(d => d.key === key[0]) || {};

	//获取所有上级栏目信息
	data.parents = dictionaryList.value.filter(d =>
		data.parent_ids
			.split(",")
			.map(id => parseInt(id))
			.includes(d.id)
	);

	currentNode.value = data;
	emit("select", currentNode.value);
};

const parentDictionaryTree = computed(() => {
	const filter = (tree, data = []) => {
		if (!tree.length) return [];

		for (const item of tree) {
			if (item.id === formState.value.id) continue;

			if (item.children && item.children.length > 0) item.children = filter(item.children, []);
			data.push(item);
		}

		return data;
	};

	return filter([
		{
			...dictionaryRoot.value,
			children: JSON.parse(JSON.stringify(dictionaryTree.value))
		}
	]);
});

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});

const parentTreeData = computed(() => {
	const filter = (tree, data = []) => {
		if (!tree.length) return [];

		for (const item of tree) {
			if (item.value === formState.value.value) continue;

			if (item.children && item.children.length > 0) item.children = filter(item.children, []);
			data.push(item);
		}

		return data;
	};

	return filter(JSON.parse(JSON.stringify(dictionaryTree.value)));
});
</script>
